package com.marvels.loanapply.controller;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.marvels.common.dto.MarvelsResultDTO;
import com.marvels.common.exception.MarvelsBusinessException;
import com.marvels.common.exception.MarvelsErrorCode;
import com.marvels.common.utils.MarvelsLogUtil;
import com.marvels.loanapply.api.LoanapplyCheckBillApi;
import com.marvels.loanapply.dto.ChannelCostDTO;
import com.marvels.loanapply.dto.CheckBillDTO;
import com.marvels.loanapply.dto.FlowStatisticsDTO;
/**
 * 对账管理
 * @author 刘琴
 * 2018年10月10日
 */
@RequestMapping("/loanApply/checkBill")
@RestController
public class CheckBillController {
	
	@Autowired
	private LoanapplyCheckBillApi checkBillApi;
	/**
	 * 流量统计
	 * @param dto
	 * @return
	 */
	@RequestMapping("flowStatistics")
	@ResponseBody
	public MarvelsResultDTO flowStatistics(@RequestBody CheckBillDTO dto){
		List<FlowStatisticsDTO> list = null;
		try {
			list = checkBillApi.selectFlowStatistics(dto);
		}catch (MarvelsBusinessException e) {
			MarvelsLogUtil.getInstance().error(">>>>>>流量统计查询list的筛选FAIL:", e);
			return MarvelsResultDTO.getResult(MarvelsErrorCode.FAIL.getValue(), MarvelsErrorCode.FAIL.getDesc(), null);
		}catch(Exception e){
			MarvelsLogUtil.getInstance().error("[flowStatistics] error: ",e);
			return MarvelsResultDTO.getResult(MarvelsErrorCode.ERROR.getValue(), MarvelsErrorCode.ERROR.getDesc(), e);
		}
		return MarvelsResultDTO.getResult(MarvelsErrorCode.SUCCESS.getValue(), MarvelsErrorCode.SUCCESS.getDesc(), list);
	}
	
	
	@RequestMapping("selectUserIdByName")
	@ResponseBody
	public String selectUserIdByName(@RequestParam(value ="userName",required = true)String userName){
		if (StringUtils.isBlank(userName)) {
			return null;
		}
		
		userName = userName.trim().replaceAll(" ", "");
		
		if (StringUtils.isBlank(userName)) {
			return null;
		}
		String userIds = checkBillApi.selectUserIdByName(userName);
		if(StringUtils.isBlank(userIds)){
			return null;
		}
		return userIds;
	}
	
	@RequestMapping("selectUserNameByPhone")
	@ResponseBody
	public String selectUserNameByPhone(String mobile){
		return checkBillApi.selectUserNameByPhone(mobile);			
	}
	
	@RequestMapping("selectUserNameByPhone1")
	@ResponseBody
	public Map<String,String> selectUserNameByPhone1(@RequestBody String mobiles){
		return checkBillApi.selectUserNameByPhone1(mobiles);			
	}
	
	
	@RequestMapping("/downLoadFlowStatisticsExcel")
	public void excelFlowStatisticsDownload(CheckBillDTO dto,HttpServletResponse response,HttpServletRequest request){
		BufferedOutputStream output = null;
		ByteArrayOutputStream byteArrayOutputStream=null;
		try {
			String fileName = "流量统计.xls";
			HSSFWorkbook wb = checkBillApi.findFlowStatisticsExcelWorkbook(dto);
			byteArrayOutputStream = new ByteArrayOutputStream();
			wb.write(byteArrayOutputStream);
			byte[] bs = byteArrayOutputStream.toByteArray();
			byteArrayOutputStream.flush();
			byteArrayOutputStream.close();
			response.setContentType("application/octet-stream;charset=ISO8859-1");
			
			output = new BufferedOutputStream(response.getOutputStream());
			// 中文文件名必须转码为 ISO8859-1,否则为乱码
			String fileNameDown = new String(fileName.getBytes(), "ISO8859-1");
			// 作为附件下载
			response.setHeader("Content-Disposition", "attachment;filename=" + fileNameDown);
			
			output.write(bs);
			response.flushBuffer();
			output.close();
			
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>下载流量统计--查询列表异常:", e);
		}
		finally {
			if(byteArrayOutputStream!=null){
				try {
					byteArrayOutputStream.close();
				} catch (IOException e) {
					MarvelsLogUtil.getInstance().error(">>>>>>>>>关闭输出流异常byteArrayOutputStream", e);
				}
			}
			if (output != null)
				try {
					output.close();
				} catch (IOException e) {
					MarvelsLogUtil.getInstance().error(">>>>>>>>>关闭输出流异常output", e);
				}
		}
		
	}
	/**
	 * 获取该时间段内指定续贷用户
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	@RequestMapping("selectContinueLoanUser")
	@ResponseBody
	public String selectContinueLoanUser(@RequestBody CheckBillDTO dto){
		String startDate = dto.getStartDate();
		String endDate = dto.getEndDate();
		return checkBillApi.selectContinueLoanUser(startDate,endDate);			
	}
	
	
	/**
	 * 获取该时间段内指定续贷用户
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	@RequestMapping("synchroMoneyHandOutTime")
	@ResponseBody
	public String synchroMoneyHandOutTime(@RequestBody String loanId){
		MarvelsLogUtil.getInstance().info("synchroMoneyHandOutTime:loanId="+loanId);
		String reloanFlag =  checkBillApi.synchroMoneyHandOutTime(loanId);		
		return reloanFlag;
	}
	
	
	
	
	/**
	 * 渠道成本
	 * @param dto
	 * @return
	 */
	@RequestMapping("channelCost")
	@ResponseBody
	public MarvelsResultDTO channelCost(@RequestBody CheckBillDTO dto){
		List<ChannelCostDTO> list = null;
		try {
			list = checkBillApi.channelCost(dto);
		}catch (MarvelsBusinessException e) {
			MarvelsLogUtil.getInstance().error(">>>>>>渠道成本查询list的筛选FAIL:", e);
			return MarvelsResultDTO.getResult(MarvelsErrorCode.FAIL.getValue(), MarvelsErrorCode.FAIL.getDesc(), null);
		}catch(Exception e){
			MarvelsLogUtil.getInstance().error("[channelCost] error: ",e);
			return MarvelsResultDTO.getResult(MarvelsErrorCode.ERROR.getValue(), MarvelsErrorCode.ERROR.getDesc(), e);
		}
		return MarvelsResultDTO.getResult(MarvelsErrorCode.SUCCESS.getValue(), MarvelsErrorCode.SUCCESS.getDesc(), list);
	}
	
	
	
	/**
	 * excel下载
	 * @param listQueryConditionDto
	 * @return
	 */
	@RequestMapping("channelCostDownLoad")
	public void channelCostDownLoad(CheckBillDTO dto,HttpServletRequest request,HttpServletResponse response){
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/vnd.ms-excel");
		OutputStream outs = null;
		try {
			response.setHeader("Content-disposition", "attachment; filename="+ new String("渠道成本一览表.xls".getBytes("UTF-8"),"ISO8859-1"));
			HSSFWorkbook downLoadDeal2 = checkBillApi.channelCostDown(dto);
			outs = response.getOutputStream();// 获取文件输出IO流
			downLoadDeal2.write(outs);
		}catch (MarvelsBusinessException e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>下载渠道成本数据FAIL:", e);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>下载渠道成本数据异常", e);
		}finally{
			try {
				outs.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
